package migrations

import (
	"fmt"

	"go.uber.org/zap"
	"gorm.io/gorm"
)

// Bootstrap creates "migrations" table
// to keep tract of already run database migrations
func Bootstrap(db *gorm.DB) error {
	migrationName := "bootstrap_migrations"

	migration := new(Migration)

	// Using Error instead of RecordNotFound because we want to check
	// if the migrations table exists. This is different from later migrations
	// where we query the already create migrations table.
	result := db.Where("name = ?", migrationName).First(migration)
	exists := nil == result.Error

	lg, _ := zap.NewProduction()
	defer lg.Sync() // flushes buffer, if any
	sg := lg.Sugar()

	if exists {
		sg.Infof("Skipping %s migration", migrationName)
		return nil
	}

	//create table
	if err := db.AutoMigrate(new(Migration)); err != nil {
		return fmt.Errorf("Error creating migrations table: %s", err.Error())
	}

	// Save a record to migrations table,
	// so we don't return this migration again
	create := db.Create(migration)
	err := create.Error
	if err != nil {
		return fmt.Errorf("Error saving record to migrations table: %s", err.Error())
	}
	return nil
}
